package com.zhanghe.im.handler;

import com.zhanghe.im.request.CreateGroupRequestPacket;
import com.zhanghe.im.response.CreateGroupResPonsePacket;
import com.zhanghe.im.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class SimpleCreateGroupRequestHandler extends SimpleChannelInboundHandler<CreateGroupRequestPacket> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CreateGroupRequestPacket msg) throws Exception {
        List<String> users = msg.getUsers();
        //创建一个channel分组
        ChannelGroup channelGroup = new DefaultChannelGroup(ctx.executor());

        List<String> userNames = new ArrayList<>();
        for(String userId:users){
            Channel channel = SessionUtil.getChannel(userId);
            if(channel!=null){
                channelGroup.add(channel);
                userNames.add(SessionUtil.getSession(channel).getUserName());
            }
        }
        String groupId = UUID.randomUUID().toString();
        CreateGroupResPonsePacket createGroupResPonsePacket = new CreateGroupResPonsePacket();
        createGroupResPonsePacket.setGroupId(groupId);
        createGroupResPonsePacket.setUserNames(userNames);
        createGroupResPonsePacket.setResult(true);
        //给每个客户端发送拉群通知
        channelGroup.writeAndFlush(createGroupResPonsePacket);
        SessionUtil.addChannelGroup(groupId,channelGroup);
        System.out.print("群创建成功，id 为[" + createGroupResPonsePacket.getGroupId() + "], ");
        System.out.println("群里面有：" + createGroupResPonsePacket.getUserNames());
    }

}
